package com.gitee.sunshine.factory;

import java.util.Stack;

import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StackContext implements ServiceInvocationContext {

	private static final Logger LOGGER = LoggerFactory.getLogger(StackContext.class);

	public static final String TRANSACTIONID_FORMAT_STRING = "%s-%s-%s";

	private Stack<InvocationStatus> invocationStatusStack = new Stack<InvocationStatus>();

	@Override
	public InvocationStatus createInvocation(MethodInvocation invocation) {
		InvocationStatus invocationStatus = new InvocationStatus();
		invocationStatus.setSequenceId(createTransactionId());
		invocationStatus.setClassName(invocation.getClass().getName());
		invocationStatus.setMethodName(invocation.getMethod().getName());
		this.invocationStatusStack.push(invocationStatus);
		return invocationStatus;
	}

	@Override
	public InvocationStatus endCurrentInvocation(MethodInvocation invocation) {
		LOGGER.info("invocationStatusStack pop before size：{}", invocationStatusStack.size());
		this.invocationStatusStack.pop();
		LOGGER.info("invocationStatusStack pop after size：{}", invocationStatusStack.size());
		return null;
	}

	@Override
	public boolean serviceEnd() {
		boolean status = false;
		if (this.invocationStatusStack.isEmpty()) {
			status = true;
			LOGGER.info("invocationStatusStack had null");
		}
		return status;
	}

	@Override
	public void clean() {
		this.invocationStatusStack = new Stack<InvocationStatus>();
	}

	private String createTransactionId() {
		String threadName = String.valueOf(Thread.currentThread().getId());
		String formatTransactionId = String.format(TRANSACTIONID_FORMAT_STRING, threadName,
				String.valueOf(System.currentTimeMillis()), String.valueOf((int) Math.floor(Math.random() * 10000)));
		LOGGER.info("创建任务id构造成功为：{}", formatTransactionId);
		return formatTransactionId;
	}

}
